package com.liping.www.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liping.www.entity.User;
import com.liping.www.service.UserService;
import com.liping.www.util.RespResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    protected UserService userService;

    //修改密码
    @PostMapping("/savePassword")
    @ResponseBody
    public RespResult savePassword(HttpSession session, String oldPass, String newPass, String newPass2) {
        User loginUser = (User) session.getAttribute("loginUser");
        if (!(oldPass.equals(userService.findUserByUserAccount(loginUser).getUserPwd()))) {
            return RespResult.fail("旧密码错误！");
        } else if (newPass.equals(oldPass)) {
            return RespResult.fail("新旧密码不能相同！");
        } else if (newPass.equals(newPass2)) {
            return RespResult.fail("两次输入的密码不一致！");
        }
        loginUser.setUserPwd(newPass);
        userService.saveOrUpdate(loginUser);
        return RespResult.success("修改成功！");
    }

    //修改个人资料
    @PostMapping("/saveProfile")
    @ResponseBody
    public RespResult saveProfile(HttpSession session, User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", user.getId());
        if (!(userService.update(user, queryWrapper))) {
            return RespResult.fail("修改异常！");
        }
        session.setAttribute("loginUser", userService.getById(user.getId()));
        return RespResult.success("修改成功！");
    }
}
